import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_wisave/widgets/indicator.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import 'package:flutter_wisave/Common/TimeSwitching.dart';
import '../../Tools/ToolsLocalStorage.dart';
import '../../widgets/AppColors.dart';

class ProductionDetailPage extends StatefulWidget {
  final int initialIndex;

  const ProductionDetailPage({
    super.key,
    this.initialIndex = 0,
  });

  @override
  State<ProductionDetailPage> createState() => _ProductionDetailPageState();
}

class _ProductionDetailPageState extends State<ProductionDetailPage>
    with SingleTickerProviderStateMixin {
  final NetworkService _networkService = NetworkService();
  DateTime _currentMonthDateTime = DateTime.now();
  late String currentMonthDate;
  List<dynamic> _prediction = [];
  late String startDate;
  late String endDate;

  @override
  void initState() {
    super.initState();
    _networkService.setupInterceptors(context);
    currentMonthDate = _formatMonthDate(_currentMonthDateTime);
    _loadDataRatio();
  }

  void _onDayDateChanged(DateTime newDate) {
    setState(() {
      _currentMonthDateTime = newDate;
      currentMonthDate = _formatMonthDate(_currentMonthDateTime);
      _loadDataRatio();
    });
  }

  String _formatMonthDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}';
  }

  void _onMonthDateChanged(DateTime newDate) {
    setState(() {
      _currentMonthDateTime = newDate;
      currentMonthDate = _formatMonthDate(_currentMonthDateTime);
      startDate =
          DateTime(_currentMonthDateTime.year, _currentMonthDateTime.month, 1)
              .toString()
              .split(' ')[0];
      endDate = DateTime(
              _currentMonthDateTime.year, _currentMonthDateTime.month + 1, 0)
          .toString()
          .split(' ')[0];
      _loadDataRatio();
    });
  }

  //各班组产能预测
  Future<void> _loadDataRatio() async {
    try {
      final result = await _fetchDataRatio();
      if (result['code'] == 200) {
        setState(() {
          _prediction = (result['rows'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
        });
      } else {
        print('Error: ${result['msg']}');
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<dynamic> _fetchDataRatio() async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      final response = await _networkService.get(
          '/plcTimer/teampdicount/steelOutRatio?companyId=$deptID&date=$currentMonthDate');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('steeloutday Failed to load data');
      }
    } catch (e) {
      print('steeloutday Error in _fetchDataM: $e');
      rethrow;
    }
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent, // 状态栏颜色
    ));

    // 获取屏幕的宽度和高度
    final mediaQuery = MediaQuery.of(context);
    final screenWidth = mediaQuery.size.width;

    return Scaffold(
        backgroundColor: AppColors.backgroundColor,
        appBar: AppBar(
          title: const Text('班组月产量排名'),
          foregroundColor: AppColors.textPrimary,
          centerTitle: true,
          backgroundColor: Colors.transparent, // Make AppBar transparent
          flexibleSpace: Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/home/home_topbg.png'),
                fit: BoxFit.cover,
              ),
            ),
          ),
        ),
        body: Stack(children: [
          Padding(
            padding: const EdgeInsets.all(15.0),
            child: Container(
              padding: const EdgeInsets.all(16.0),
              height: 400,
              decoration: BoxDecoration(
                color: AppColors.cardColor,
                borderRadius: BorderRadius.circular(8.0),
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.2),
                    blurRadius: 6.0,
                  ),
                ],
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  TimeSwitching(
                    mode: SwitchingMode.month,
                    onDateChanged: _onDayDateChanged,
                  ),
                  const SizedBox(height: 10),
                  SizedBox(
                    width: double.infinity,
                    child: Center(
                      child: PieChartSample3(
                        prediction: _prediction,
                      ),
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      if (_prediction.length > 0)
                        Indicator(
                          color: Color(0xFF2AB6F7),
                          text: _prediction[0]['team'].toString(),
                          isSquare: true,
                        ),
                      SizedBox(width: 20),
                      if (_prediction.length > 1)
                        Indicator(
                          color: Color(0xFF814FF3),
                          text: _prediction[1]['team'].toString(),
                          isSquare: true,
                        ),
                      SizedBox(width: 20),
                      if (_prediction.length > 2)
                        Indicator(
                          color: Color(0xFF53E0B1),
                          text: _prediction[2]['team'].toString(),
                          isSquare: true,
                        ),
                      SizedBox(width: 20),
                      if (_prediction.length > 3)
                        Indicator(
                          color: Color(0xFFFD5864),
                          text: _prediction[3]['team'].toString(),
                          isSquare: true,
                        ),
                      SizedBox(width: 20),
                      if (_prediction.length > 4)
                        Indicator(
                          color: Color(0xFFFD5864),
                          text: _prediction[4]['team'].toString(),
                          isSquare: true,
                        ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ]));
  }
}

class PieChartSample3 extends StatefulWidget {
  final List<dynamic>? prediction;
  const PieChartSample3({super.key, this.prediction});

  @override
  State<StatefulWidget> createState() => PieChart3State();
}

class PieChart3State extends State<PieChartSample3> {
  int touchedIndex = -1;

  @override
  Widget build(BuildContext context) {
    final mediaQuery = MediaQuery.of(context);
    final screenWidth = mediaQuery.size.width;

    return AspectRatio(
      aspectRatio: 1.3,
      child: Stack(
        children: <Widget>[
          Positioned(
            left: (screenWidth - 180) / 2,
            top: 80,
            width: 100,
            height: 100,
            child: Center(
              child: AspectRatio(
                aspectRatio: 1,
                child: Stack(
                  children: [
                    PieChart(
                      PieChartData(
                        pieTouchData: PieTouchData(
                          touchCallback:
                              (FlTouchEvent event, pieTouchResponse) {
                            setState(() {
                              if (!event.isInterestedForInteractions ||
                                  pieTouchResponse == null ||
                                  pieTouchResponse.touchedSection == null) {
                                touchedIndex = -1;
                                return;
                              }
                              touchedIndex = pieTouchResponse
                                  .touchedSection!.touchedSectionIndex;
                            });
                          },
                        ),
                        borderData: FlBorderData(
                          show: false,
                        ),
                        sectionsSpace: 5,
                        centerSpaceRadius: 70,
                        sections: showingSections(widget.prediction ?? []),
                      ),
                    ),
                    Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            '${_calculateTotalPdi(widget.prediction ?? [])}',
                            style: TextStyle(
                              fontSize: 20,
                              color: AppColors.textPrimary,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          Text(
                            '总数',
                            style: TextStyle(
                              fontSize: 16,
                              color: AppColors.textSecondary,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  List<PieChartSectionData> showingSections(List<dynamic> data) {
    return List.generate(data.length, (i) {
      final isTouched = i == touchedIndex;
      final fontSize = 10.0;
      final radius = 18.0;
      const shadows = [Shadow(color: Colors.black, blurRadius: 11)];
      final bgcolos = [
        Color(0xFF2AB6F7),
        Color(0xFF814FF3),
        Color(0xFF53E0B1),
        Color(0xFFFCAA3F),
        Color(0xFFFD5864),
      ];
      return PieChartSectionData(
          color: bgcolos[i],
          value: data[i]['ratio'],
          title: data[i]['ratio'].toString() + '%',
          radius: radius,
          titleStyle: TextStyle(
            fontSize: fontSize,
            fontWeight: FontWeight.bold,
            color: Colors.black,
          ));
    });
  }
}

class PieChartSample2 extends StatefulWidget {
  const PieChartSample2({super.key});

  @override
  State<StatefulWidget> createState() => PieChart2State();
}

class PieChart2State extends State {
  int touchedIndex = -1;

  @override
  Widget build(BuildContext context) {
    return AspectRatio(
      aspectRatio: 1,
      child: Stack(
        children: <Widget>[
          Positioned(
            left: 15,
            top: 10,
            width: 180,
            height: 180,
            child: Center(
              child: AspectRatio(
                aspectRatio: 1,
                child: PieChart(
                  PieChartData(
                    pieTouchData: PieTouchData(
                      touchCallback: (FlTouchEvent event, pieTouchResponse) {
                        setState(() {
                          if (!event.isInterestedForInteractions ||
                              pieTouchResponse == null ||
                              pieTouchResponse.touchedSection == null) {
                            touchedIndex = -1;
                            return;
                          }
                          touchedIndex = pieTouchResponse
                              .touchedSection!.touchedSectionIndex;
                        });
                      },
                    ),
                    borderData: FlBorderData(
                      show: false,
                    ),
                    sectionsSpace: 0,
                    centerSpaceRadius: 90,
                    sections: showingSections(),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  List<PieChartSectionData> showingSections() {
    return List.generate(2, (i) {
      final isTouched = i == touchedIndex;
      final fontSize = isTouched ? 25.0 : 20.0;
      final radius = 10.0;
      const shadows = [Shadow(color: Colors.black, blurRadius: 11)];
      switch (i) {
        case 0:
          return PieChartSectionData(
            color: Color(0xFFF1F1F1),
            value: 40,
            showTitle: false,
            radius: radius,
          );
        case 1:
          return PieChartSectionData(
            gradient: LinearGradient(
              colors: [
                Color.fromARGB(255, 6, 180, 248),
                Color(0xFFF1F1F1),
              ],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
            value: 60,
            showTitle: false,
            radius: radius,
          );
        default:
          throw Error();
      }
    });
  }
}

// 计算 totalPdi 的总和
double _calculateTotalPdi(List<dynamic> prediction) {
  return prediction.fold(0, (sum, item) => sum + (item['totalPdi'] ?? 0));
}
